package richbar.com.richbar.adapter.shopping;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.common.base.BaseActivity;
import com.common.util.ToastUtil;
import com.okhttp.GlideUtil;
import com.okhttp.network.HttpUtils;
import com.okhttp.network.MyGson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import richbar.com.richbar.R;
import richbar.com.richbar.activity.login.LoginAc;
import richbar.com.richbar.activity.product.FirmOrderAc;
import richbar.com.richbar.activity.product.FirmOrderShopCartAc;
import richbar.com.richbar.base.BaseApplication;
import richbar.com.richbar.bean.GoodsBean;
import richbar.com.richbar.bean.NumBean;
import richbar.com.richbar.bean.ShopCartListBean;
import richbar.com.richbar.bean.TotalBean;
import richbar.com.richbar.fragment.ShoppingCartFragment;
import richbar.com.richbar.util.LoadingDialog;
import richbar.com.richbar.util.NetWorkUtil;
import richbar.com.richbar.util.Util;

/**
 * Created by qyang on 2018-9-13.
 */

public class ShoppingAdapter extends BaseExpandableListAdapter {
    private Activity activity;
    private List<ShopCartListBean.DataBean.ListBean> groups;
    private List<List<ShopCartListBean.DataBean.ListBean.GoodsBean>> childs;
    private LoadingDialog dialog;
    private Map<Integer, Boolean> groupSelect;
    private List<Map<Integer, Boolean>> childSelect;
    private List<Map<Integer, Boolean>> childDelSelect;
    private CheckBox checkBox;
    private CheckBox checkDelBox;
    private TextView tvs;
    private boolean isVisble = false;
    private Map<Integer, Boolean> groupDelSelect = new HashMap<>();
    ShoppingCartFragment fragment;

    public ShoppingAdapter(final ShoppingCartFragment fragment, final Activity activity, final List<ShopCartListBean.DataBean.ListBean> groups, final List<List<ShopCartListBean.DataBean.ListBean.GoodsBean>> child, final Map<Integer, Boolean> groupSelect, List<Map<Integer, Boolean>> childSelects, List<Map<Integer, Boolean>> childdelSelects, final CheckBox checkBox, final CheckBox checkdelBox, final TextView tv, final TextView tv_finish, final TextView tv_delete, final TextView tv_edit, TextView buy) {
        this.activity = activity;
        this.groups = groups;
        this.childs = child;
        this.groupSelect = groupSelect;
        this.childSelect = childSelects;
        childDelSelect = childdelSelects;
        this.checkBox = checkBox;
        checkDelBox = checkdelBox;
        this.fragment = fragment;
        tvs = tv;
        dialog = new LoadingDialog(activity, 0);
        checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String dos = "";
                if (checkBox.isChecked()) {
                    dos = "select";
                } else {
                    dos = "cancelselect";
                }
                dialog.show();
                NetWorkUtil.setSpSelect(Util.md5(), BaseApplication.uid, "3", dos, "", new HttpUtils.HttpCallback() {
                    @Override
                    public void onSuccess(String data) {
                        dialog.dismiss();
                        final TotalBean totalBean = MyGson.getInstance().fromJson(data, TotalBean.class);
                        tvs.setText("合计：" + totalBean.getData().getTotal() + "元");
                    }

                    @Override
                    public void onError(String msg) {
                        super.onError(msg);
                        dialog.dismiss();
                    }
                });
                if (checkBox.isChecked()) {
                    for (int i = 0; i < groups.size(); i++) {
                        groupSelect.put(i, true);
                        for (int j = 0; j < childs.get(i).size(); j++) {
                            childSelect.get(i).put(j, true);
                        }
                    }
                } else {
                    for (int i = 0; i < groups.size(); i++) {
                        for (int j = 0; j < childs.get(i).size(); j++) {
                            childSelect.get(i).remove(j);
                        }
                        groupSelect.remove(i);
                    }
                }

                notifyDataSetChanged();
            }
        });
        checkDelBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkDelBox.isChecked()) {
                    for (int i = 0; i < groups.size(); i++) {
                        groupDelSelect.put(i, true);
                        for (int j = 0; j < childs.get(i).size(); j++) {
                            childDelSelect.get(i).put(j, true);
                        }
                    }
                } else {
                    for (int i = 0; i < groups.size(); i++) {
                        for (int j = 0; j < childs.get(i).size(); j++) {
                            childDelSelect.get(i).remove(j);
                        }
                        groupDelSelect.remove(i);
                    }
                }

                notifyDataSetChanged();
            }
        });
        tv_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_finish.setVisibility(View.VISIBLE);
                tv_delete.setVisibility(View.VISIBLE);
                tv_edit.setVisibility(View.GONE);
                checkdelBox.setVisibility(View.VISIBLE);
                checkBox.setVisibility(View.GONE);
                isVisble = true;
                notifyDataSetChanged();

            }
        });
        tv_finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_finish.setVisibility(View.GONE);
                tv_delete.setVisibility(View.GONE);
                tv_edit.setVisibility(View.VISIBLE);
                checkdelBox.setVisibility(View.GONE);
                checkBox.setVisibility(View.VISIBLE);
                isVisble = false;
                notifyDataSetChanged();
            }
        });
        tv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String type = "";
                String id = "";
                if (checkdelBox.isChecked()) {//全部删除
                    type = "3";
                    id = "0";
                } else {
                    boolean b = false;
                    for (Integer key : groupDelSelect.keySet()) {//删除选中的店铺
                        if (groupDelSelect.get(key)) {
                            id = id + groups.get(key).getSellerid() + ",";
                            b = true;
                            type = "2";
                        }

                    }
                    if (!b) {//如果店铺没有选中 则是单个商品删除
                        type = "1";
                        for (int i = 0; i < groups.size(); i++) {
                            for (Integer key : childDelSelect.get(i).keySet()) {//删除选中的店铺
                                if (childDelSelect.get(i).get(key)) {
                                    id = id + child.get(i).get(key).getCart_id() + ",";
                                }

                            }
                        }
                    }

                }
                dialog.show();
                NetWorkUtil.delCart(BaseApplication.uid, id, type, Util.md5(), new HttpUtils.HttpCallback() {
                    @Override
                    public void onSuccess(String data) {
                        dialog.dismiss();
                        fragment.DelShopCartResh();
                    }

                    @Override
                    public void onError(String msg) {
                        super.onError(msg);
                        dialog.dismiss();
                        ToastUtil.showToast(activity, msg);
                    }
                });

            }
        });
        buy.setOnClickListener(new View.OnClickListener() {//去结算
            @Override
            public void onClick(View v) {
                boolean b = false;
                for (int i = 0; i < childSelect.size(); i++) {//判断是否至少选中一个商品
                    if (childSelect.get(i).size() > 0) {
                        b = true;
                    }
                }
                if (b) {
                    ShoppingCartFragment.sendBraodcast(activity);
                   activity.startActivity(new Intent(activity,FirmOrderShopCartAc.class));

                } else {
                    ToastUtil.showToast(activity, "至少选中一个商品");
                }


//               start(FirmOrderAc.class, new BaseActivity.OnBundleListener() {
//                    @Override
//                    public Bundle onSetBundle(Bundle bundle) {
//                      bundle.putSerializable("bean", bean);
//                        return bundle;
//                    }
//                });
            }
        });

    }

    @Override
    public int getGroupCount() {
        return groups.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return childs.get(groupPosition).size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return groups.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return childs.get(groupPosition).get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        final GroupViewHolder holder;
        if (null == convertView) {
            convertView = LayoutInflater.from(activity).inflate(R.layout.item_shopping_card_parent, parent, false);
            holder = new GroupViewHolder();
            holder.name = convertView.findViewById(R.id.name);
            holder.select = convertView.findViewById(R.id.select);
            holder.select_delete = convertView.findViewById(R.id.select_delete);
            convertView.setTag(holder);
        } else {
            holder = (GroupViewHolder) convertView.getTag();
        }
        holder.name.setText(groups.get(groupPosition).getSellername());
        if (isVisble) {
            holder.select.setVisibility(View.GONE);
            holder.select_delete.setVisibility(View.VISIBLE);
        } else {
            holder.select.setVisibility(View.VISIBLE);
            holder.select_delete.setVisibility(View.GONE);
        }
        holder.select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String dos = "";
                if (holder.select.isChecked()) {
                    groupSelect.put(groupPosition, true);
                    dos = "select";
                } else {
                    groupSelect.remove(groupPosition);
                    dos = "cancelselect";
                }
                dialog.show();
                NetWorkUtil.setSpSelect(Util.md5(), BaseApplication.uid, "1", dos, groups.get(groupPosition).getSellerid() + "", new HttpUtils.HttpCallback() {
                    @Override
                    public void onSuccess(String data) {
                        dialog.dismiss();
                        final TotalBean totalBean = MyGson.getInstance().fromJson(data, TotalBean.class);
                        tvs.setText("合计：" + totalBean.getData().getTotal() + "元");
                    }

                    @Override
                    public void onError(String msg) {
                        super.onError(msg);
                        dialog.dismiss();
                        ToastUtil.showToast(activity, msg);
                    }
                });
                if (holder.select.isChecked()) {
                    for (int i = 0; i < childs.get(groupPosition).size(); i++) {
                        childSelect.get(groupPosition).put(i, true);
                    }
                } else {
                    childSelect.get(groupPosition).clear();
                }
                notifyDataSetChanged();
                if (groupSelect.size() == groups.size()) {
                    checkBox.setChecked(true);
                } else {
                    checkBox.setChecked(false);
                }

            }
        });

        if (groupSelect != null && groupSelect.containsKey(groupPosition)) {
            holder.select.setChecked(true);
        } else {
            holder.select.setChecked(false);
        }

        holder.select_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (holder.select_delete.isChecked()) {
                    groupDelSelect.put(groupPosition, true);
                } else {
                    groupDelSelect.remove(groupPosition);
                }
                if (holder.select_delete.isChecked()) {
                    for (int i = 0; i < childs.get(groupPosition).size(); i++) {
                        childDelSelect.get(groupPosition).put(i, true);
                    }
                } else {
                    childDelSelect.get(groupPosition).clear();
                }
                notifyDataSetChanged();
                if (groupDelSelect.size() == groups.size()) {
                    checkDelBox.setChecked(true);
                } else {
                    checkDelBox.setChecked(false);
                }
            }
        });
        if (groupDelSelect.size() > 0 && groupDelSelect != null && groupDelSelect.containsKey(groupPosition)) {
            holder.select_delete.setChecked(true);
        } else {
            holder.select_delete.setChecked(false);
        }

        return convertView;
    }

    @Override
    public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        final ChildViewHolder holder;
        if (null == convertView) {
            convertView = LayoutInflater.from(activity).inflate(R.layout.item_shopping_card_child, parent, false);
            holder = new ChildViewHolder();
            holder.name = convertView.findViewById(R.id.name);
            holder.select = convertView.findViewById(R.id.select);
            holder.pic = convertView.findViewById(R.id.pic);
            holder.price = convertView.findViewById(R.id.price);
            holder.select_delete = convertView.findViewById(R.id.select_delete);
            holder.tv_minute = convertView.findViewById(R.id.tv_minute);
            holder.tv_plus = convertView.findViewById(R.id.tv_plus);
            holder.edit_num = convertView.findViewById(R.id.edit_nums);
            holder.ly = convertView.findViewById(R.id.ly);
            convertView.setTag(holder);
        } else {
            holder = (ChildViewHolder) convertView.getTag();
        }
        if (isVisble) {
            holder.select.setVisibility(View.GONE);
            holder.select_delete.setVisibility(View.VISIBLE);
        } else {
            holder.select.setVisibility(View.VISIBLE);
            holder.select_delete.setVisibility(View.GONE);
        }
        holder.select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String dos = "";
                if (holder.select.isChecked()) {
                    childSelect.get(groupPosition).put(childPosition, true);
                    dos = "select";
                } else {
                    childSelect.get(groupPosition).remove(childPosition);
                    dos = "cancelselect";
                }
                dialog.show();
                NetWorkUtil.setSpSelect(Util.md5(), BaseApplication.uid, "2", dos, childs.get(groupPosition).get(childPosition).getCart_id() + "", new HttpUtils.HttpCallback() {
                    @Override
                    public void onSuccess(String data) {
                        dialog.dismiss();
                        final TotalBean totalBean = MyGson.getInstance().fromJson(data, TotalBean.class);
                        tvs.setText("合计：" + totalBean.getData().getTotal() + "元");
                    }

                    @Override
                    public void onError(String msg) {
                        super.onError(msg);
                        dialog.dismiss();
                        ToastUtil.showToast(activity, msg);
                    }
                });
                if (!holder.select.isChecked()) {
                    groupSelect.remove(groupPosition);
                    notifyDataSetChanged();
                } else {
                    if (childSelect.get(groupPosition).size() == childs.get(groupPosition).size()) {
                        groupSelect.put(groupPosition, true);
                        notifyDataSetChanged();
                    }
                }
                if (groupSelect.size() == groups.size()) {
                    checkBox.setChecked(true);
                } else {
                    checkBox.setChecked(false);
                }
            }
        });

        if (childSelect.get(groupPosition) != null && childSelect.get(groupPosition).containsKey(childPosition)) {
            holder.select.setChecked(true);
        } else {
            holder.select.setChecked(false);
        }
        holder.edit_num.setText(childs.get(groupPosition).get(childPosition).getGoods_num() + "");
        holder.price.setText(childs.get(groupPosition).get(childPosition).getGoods_price());
        holder.name.setText(childs.get(groupPosition).get(childPosition).getGoods_name());
        GlideUtil.loadImage(activity, NetWorkUtil.URL + childs.get(groupPosition).get(childPosition).getGoods_img(), holder.pic);
        holder.select_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (holder.select_delete.isChecked()) {
                    childDelSelect.get(groupPosition).put(childPosition, true);
                } else {
                    childDelSelect.get(groupPosition).remove(childPosition);
                }
                if (!holder.select_delete.isChecked()) {
                    groupDelSelect.remove(groupPosition);
                    notifyDataSetChanged();
                } else {
                    if (childDelSelect.get(groupPosition).size() == childs.get(groupPosition).size()) {
                        groupDelSelect.put(groupPosition, true);
                        notifyDataSetChanged();
                    }
                }
            }
        });
        if (childDelSelect.get(groupPosition) != null && childDelSelect.get(groupPosition).containsKey(childPosition)) {
            holder.select_delete.setChecked(true);
        } else {
            holder.select_delete.setChecked(false);
        }
        holder.ly.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int n = Integer.valueOf(holder.edit_num.getText().toString());
                if (n > 1) {
                    n = n - 1;
                }
                NetWorkUtil.UpdateCart(BaseApplication.uid, childs.get(groupPosition).get(childPosition).getCart_id() + "", n + "", Util.md5(), new HttpUtils.HttpCallback() {
                    @Override
                    public void onSuccess(String data) {
                        final NumBean numBean = MyGson.getInstance().fromJson(data, NumBean.class);
                        if (numBean.getCode() == 200) {
//                            tvs.setText("合计：" + numBean.getData().getTotalPrice() + "元");
                            fragment.DelShopCartResh();
                        }
                    }

                    @Override
                    public void onError(String msg) {
                        super.onError(msg);
                        ToastUtil.showToast(activity, msg);
                    }
                });

            }

        });
        holder.tv_plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int n = Integer.valueOf(holder.edit_num.getText().toString());
                n = n + 1;
                NetWorkUtil.UpdateCart(BaseApplication.uid, childs.get(groupPosition).get(childPosition).getCart_id() + "", n + "", Util.md5(), new HttpUtils.HttpCallback() {
                    @Override
                    public void onSuccess(String data) {
                        final NumBean numBean = MyGson.getInstance().fromJson(data, NumBean.class);
                        if (numBean.getCode() == 200) {
                            //  tvs.setText("合计：" + numBean.getData().getTotalPrice() + "元");
                            fragment.DelShopCartResh();
                        }
                    }

                    @Override
                    public void onError(String msg) {
                        super.onError(msg);
                    }
                });
            }
        });

        return convertView;
    }


    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

    class GroupViewHolder {
        CheckBox select;
        CheckBox select_delete;
        TextView name;
    }

    class ChildViewHolder {
        TextView name;
        TextView price;
        CheckBox select_delete;
        CheckBox select;
        ImageView pic;
        TextView tv_minute;
        TextView tv_plus;
        EditText edit_num;
        LinearLayout ly;
    }
}
